package com.simple.core.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.simple.core.validate.ValidGroup;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.FieldNameConstants;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 实体抽象类，实现通用字段维护
 *
 * @author FanXing
 * @date 2023年01月17日 10:58
 */
@Data
@MappedSuperclass
@FieldNameConstants
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final String SOFT_DELETE_CLAUSE = Fields.deleted + " = 0";

    @NotNull(groups = ValidGroup.Edit.class, message = "id不能为空")
    @ApiModelProperty("id")
    @Id
    @GeneratedValue(generator = "snowFlakeGenerator")
    @GenericGenerator(name = "snowFlakeGenerator", strategy = "com.simple.core.util.SnowFlakeIdGenerator")
    @Column(updatable = false)
    private Long id;

    @ApiModelProperty("创建人")
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @CreatedBy
    @Column(nullable = false, updatable = false)
    private String createdBy;

    @ApiModelProperty("创建时间")
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdTime;

    @ApiModelProperty("更新人")
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @LastModifiedBy
    private String lastUpdatedBy;

    @ApiModelProperty("更新时间")
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @UpdateTimestamp
    private LocalDateTime lastUpdatedTime;

    @JsonIgnore
    private Boolean deleted;

    @PrePersist
    private void prePersist() {
        if (Objects.isNull(deleted)) deleted = false;
    }

}
